home *** CD-ROM | disk | FTP | other *** search
Text File | 1992-12-28 | 1.9 KB | 47 lines | [TEXT/Help] |
- {••••• Programming with unknown values:Two examples… The 2nd is original •••••}
-
- ;;; Problem: from the book "Functionnal programming"
- ;;; given an integer list l, built in one pass a list where each element
- ;;; is equal to the maximum element in l
-
- ;;; A first solution with an UNKNOWN VALUE
- ;;; LOOK at it with attention… max is unknown and it works !
-
- (define (rbm l)
- (letrec [((f n rest&maxc)(cons (cons max (0 rest&maxc))
- (cond (>? n (-1 rest&maxc)) n (-1 rest&maxc))))
- (rest (reduce f '(() | 0) l))
- (max (-1 rest))]
- (0 rest)))
-
- ;;; Another one, much more difficult to write in ONE PASS w/o lazyness
- ;;; and therefore Unknown Values
-
- ;;; Problem: given a binary tree whose leaf are numbers, built a tree with
- ;;; the same structure, but whose leaves are the leaves of the first
- ;;; divided by the sum of all the leaves of the first tree in ONE PASS
-
- (define leaf? number?) ;Is it a leaf ?
- (define empty? null?) ;Is it empty ?
- (define left-son 0) ;Access to left son
- (define right-son -1) ;Access to right son
- (define values cons) ;To create pseudo multiple values
- (define processed 0) ;To access first element of a Multiple Value
- (define sum -1) ;To access 2nd element of a Multiple Value
-
- (define (normalize tree)
- (letrec [((norm+sum tree)
- (cond (empty? tree) (values () 0)
- (leaf? tree) (values (/ tree TotalSum) tree)
- (let [(left (norm+sum (left-son tree)))
- (right (norm+sum (right-son tree)))]
- (values (cons (processed left) (processed right))
- (+ (sum left) (sum right))))))
- (Both (norm+sum tree))
- (ProcessedTree (processed Both))
- (TotalSum (sum Both))]
- ProcessedTree))
-
- (normalize '(((0.|1.)|3.)|((6.|8.)|2.)))
- { = ((( 0.0e+0 | 5.0e-2) | 1.5e-1) ( 3.0e-1 | 4.0e-1) | 1.0e-1) }
-